package com.ag.utils;

import java.util.Collection;

import com.ag.utils.vo.GeoCoordinate;

public class DistanceUtils {
	public static final double EARTH_RADIUS = 6378137;
	public static final int DEFAULT_UNIT_KM = 1000;
	
	public static double rad(double d) {
		return d * Math.PI / 180.0;
	}

	/**
	 * 根据两点间经纬度坐标（double值），计算两点间距离，单位为米
	 * 
	 * @param lng1
	 * @param lat1
	 * @param lng2
	 * @param lat2
	 * @return
	 */
	public static double getDistance(Object lng1, Object lat1, Object lng2, Object lat2) {
		double radLat1 = rad(DoubleUtils.parse(lat1));
		double radLat2 = rad(DoubleUtils.parse(lat2));
		double a = radLat1 - radLat2;
		double b = rad(DoubleUtils.parse(lng1)) - rad(DoubleUtils.parse(lng2));
		double s = 2 * Math.asin(Math.sqrt(
				Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000;
		return s;
	}
	
	/**
     * 格式化距离
     * @param distanceM 单位米
     * @return
     */
	public static String format(Double distanceM) {
		if(distanceM == null) {
			return "";
		}
		
		if(distanceM < 1000) {
			return distanceM + "m";
		}
		
		return DoubleUtils.div(distanceM, 1000, 1) + "km";
	}
	
	public static double formatDistanceKM(double distance) {
		return formatDistance(distance, DEFAULT_UNIT_KM);
	}

	public static double formatDistance(double distance, int unit) {
		return DoubleUtils.round(distance / unit, 2);
	}

	/**
     *  根据输入的地点坐标计算中心点
     * @param geoCoordinateList
     * @return
     */
    public static GeoCoordinate getCenterPoint(Collection<GeoCoordinate> geoCoordinateList) {
        int total = geoCoordinateList.size();
        double X = 0, Y = 0, Z = 0;
        for (GeoCoordinate g : geoCoordinateList) {
            double lat, lon, x, y, z;
            lat = g.getLat() * Math.PI / 180;
            lon = g.getLng() * Math.PI / 180;
            x = Math.cos(lat) * Math.cos(lon);
            y = Math.cos(lat) * Math.sin(lon);
            z = Math.sin(lat);
            X += x;
            Y += y;
            Z += z;
        }

        X = X / total;
        Y = Y / total;
        Z = Z / total;
        double Lon = Math.atan2(Y, X);
        double Hyp = Math.sqrt(X * X + Y * Y);
        double Lat = Math.atan2(Z, Hyp);
        return GeoCoordinate.build(Lon * 180 / Math.PI, Lat * 180 / Math.PI);
    }
    
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		double distance = getDistance(115.981409, 28.646447, 115.981529, 28.64638);
		System.out.println("Distance is:" + distance);
//		System.out.println(getDistance(100.182767, 200, 120.1091498352682, 30.33513759001055));
	}
}